package com.jyw.web.controller.system;

import com.jyw.common.annotation.Anonymous;
import com.jyw.common.annotation.Log;
import com.jyw.common.core.controller.BaseController;
import com.jyw.common.core.domain.AjaxResult;
import com.jyw.common.core.domain.CommonResult;
import com.jyw.common.core.domain.entity.SysDept;
import com.jyw.common.core.domain.entity.SysRole;
import com.jyw.common.core.domain.entity.SysUser;
import com.jyw.common.core.domain.model.SimpleDto;
import com.jyw.common.core.page.TableDataInfo;
import com.jyw.common.enums.BusinessType;
import com.jyw.common.exception.ServiceException;
import com.jyw.common.utils.DateUtils;
import com.jyw.common.utils.SecurityUtils;
import com.jyw.common.utils.StringUtils;
import com.jyw.common.utils.poi.ExcelUtil;
import com.jyw.system.domain.SysUserDept;
import com.jyw.system.domain.dto.*;
import com.jyw.system.domain.vo.SysUserPageVO;
import com.jyw.system.domain.vo.UserCacheVo;
import com.jyw.system.domain.vo.UserDeptInfoVo;
import com.jyw.system.service.ISysDeptService;
import com.jyw.system.service.ISysRoleService;
import com.jyw.system.service.ISysUserDeptService;
import com.jyw.system.service.ISysUserService;
import com.jyw.system.utils.ConversionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author system
 */
@RestController
@RequestMapping("/system/user")
@Api(tags = "用户管理")
public class SysUserController extends BaseController {

    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysDeptService deptService;

    @Resource
    private ISysUserDeptService userDeptService;

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    @ApiOperation("用户列表")
    public TableDataInfo<SysUserPageVO> list(UserPageDto user) {
        startPage();
        user.setEndTime(DateUtils.toDateLastTime(user.getEndTime()));
        List<SysUserPageVO> list = userService.selectUserList(user);
        list = ConversionUtil.conversionList(list, SysUserPageVO.class);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/import/data")
    @ApiOperation("用户导入")
    public CommonResult importData(@RequestParam("file") MultipartFile file) throws Exception {
        String msg = userService.importUser(file);
        return CommonResult.success(msg);
    }

    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @GetMapping("/import/template")
    @ApiOperation("用户导入模板")
    public void importData(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("用户导入模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        IOUtils.copy(new ClassPathResource("template/excel/user_import_template.xlsx").getInputStream(), response.getOutputStream());
        response.flushBuffer();
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = {"/", "/{userId}"})
    @ApiOperation("用户详情")
    public CommonResult<SysUser> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            List<SysUserDept> allList=userDeptService.lambdaQuery().eq(SysUserDept::getUserId, userId).list();
            SysUserDept sysUserDept=allList.stream().filter(a->a.getIsDefault().intValue()==1).findFirst().orElse(null);
            if(sysUserDept!=null&&sysUserDept.getDeptId()!=null){
                sysUser.setDeptId(sysUserDept.getDeptId());
            }
            List<Long> deptIdList =allList.stream().filter(a->a.getIsDefault().intValue()==0).map(SysUserDept::getDeptId).collect(Collectors.toList());
            sysUser.setDeptIdList(deptIdList);
            return CommonResult.success(sysUser);
        }
        return CommonResult.success();
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增用户")
    public CommonResult add(@Validated @RequestBody UserAddDto addDto) {
        SysUser user = addDto.buildUser();
        if (!userService.checkUserNameUnique(user)) {
            return CommonResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return CommonResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return CommonResult.success(userService.insertUser(user, addDto.getDeptIdList()));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改用户")
    public CommonResult edit(@Validated @RequestBody UserEditDto editDto) {
        SysUser user = editDto.buildUser();
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return CommonResult.error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return CommonResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return CommonResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return CommonResult.success(userService.updateUser(user, editDto.getDeptIdList()));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    @ApiOperation("删除用户")
    public CommonResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return CommonResult.error("当前用户不能删除");
        }
        return CommonResult.success(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if(user.getPassword().length()<5){
            throw new ServiceException("密码位数最小5位");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:editState')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    @ApiOperation("状态修改")
    public CommonResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return CommonResult.success(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("/authRole/getUserRoleList")
    public TableDataInfo<SysRole> getUserRoleList(SysRolePermissionPageDto pageDto) {
        startPage();
        List<SysRole> roleList = roleService.selectRolePermission(pageDto);
        return getDataTable(roleList);
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:authRole')")
    @Log(title = "授权角色", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public CommonResult insertAuthRole(@RequestBody SysUserRoleDto roleDto) {
        userService.insertUserAuth(roleDto);
        return CommonResult.success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }

    @ApiOperation("根据手机号获取用户信息")
    @GetMapping("/info/{phoneNum}")
    @Anonymous
    public CommonResult<UserDeptInfoVo> getUserDeptInfo(@PathVariable("phoneNum") String phoneNum) {
        return CommonResult.success(userService.getUserDeptInfo(phoneNum));
    }

    @ApiOperation("获取用户缓存")
    @GetMapping("cache")
    public CommonResult<List<UserCacheVo>> cache() {
        return CommonResult.success(userService.getCache());
    }

    @ApiOperation("查询用户的所有角色id")
    @GetMapping("userRoles")
    public CommonResult<List<Long>> userRoles(Long userId) {
        List<Long> collect = roleService.selectRolesByUserId(userId).stream().filter(data->data.isFlag()).map(SysRole::getRoleId).distinct().collect(Collectors.toList());
        return CommonResult.success(collect
        );
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/list/all")
    @ApiOperation("全部用户(用户表数据,不包含部门信息)")
    @Anonymous
    public TableDataInfo<SysUser> listAll() {
        List<SysUser> list = userService.lambdaQuery().eq(SysUser::getDelFlag, '0').list();
        return getDataTable(list);
    }

    @PutMapping("/unbind")
    @ApiOperation("用户微信解绑")
    @PreAuthorize("@ss.hasPermi('system:user:unbind')")
    public CommonResult unbind(@RequestBody SimpleDto<Long> dto){
        userService.lambdaUpdate().eq(SysUser::getUserId,dto.getData())
                .set(SysUser::getOpenid,null)
                .update();
        return CommonResult.success();

    }
}
